package com.example.service;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.ext.task.list.items.TaskListItemsExtension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class MarkdownService {

    private final Parser parser;
    private final HtmlRenderer renderer;

    public MarkdownService() {
        // 配置Markdown扩展
        List<Extension> extensions = Arrays.asList(
                TablesExtension.create(),
                StrikethroughExtension.create(),
                TaskListItemsExtension.create(),
                HeadingAnchorExtension.create());

        this.parser = Parser.builder()
                .extensions(extensions)
                .build();

        this.renderer = HtmlRenderer.builder()
                .extensions(extensions)
                .escapeHtml(false) // 允许HTML标签，提升兼容性
                .build();
    }

    /**
     * 将Markdown文本转换为HTML
     */
    public String markdownToHtml(String markdown) {
        if (markdown == null || markdown.trim().isEmpty()) {
            return "";
        }

        Node document = parser.parse(markdown);
        return renderer.render(document);
    }

    /**
     * 验证Markdown语法
     */
    public boolean isValidMarkdown(String markdown) {
        try {
            if (markdown == null) {
                return false;
            }
            parser.parse(markdown);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 提取Markdown中的图片链接
     */
    public List<String> extractImageUrls(String markdown) {
        if (markdown == null) {
            return List.of();
        }

        Pattern pattern = Pattern.compile("!\\[.*?\\]\\((.*?)\\)");
        Matcher matcher = pattern.matcher(markdown);

        return matcher.results()
                .map(result -> result.group(1))
                .filter(url -> url != null && !url.trim().isEmpty())
                .toList();
    }

    /**
     * 提取Markdown中的链接
     */
    public List<String> extractLinks(String markdown) {
        if (markdown == null) {
            return List.of();
        }

        Pattern pattern = Pattern.compile("(?<!!)\\[.*?\\]\\((.*?)\\)");
        Matcher matcher = pattern.matcher(markdown);

        return matcher.results()
                .map(result -> result.group(1))
                .filter(url -> url != null && !url.trim().isEmpty())
                .toList();
    }

    /**
     * 获取Markdown文档的标题
     */
    public String extractTitle(String markdown) {
        if (markdown == null || markdown.trim().isEmpty()) {
            return null;
        }

        String[] lines = markdown.split("\n");
        for (String line : lines) {
            line = line.trim();
            if (line.startsWith("# ")) {
                return line.substring(2).trim();
            }
        }
        return null;
    }

    /**
     * 生成Markdown目录
     */
    public String generateToc(String markdown) {
        if (markdown == null || markdown.trim().isEmpty()) {
            return "";
        }

        StringBuilder toc = new StringBuilder();
        String[] lines = markdown.split("\n");

        for (String line : lines) {
            line = line.trim();
            if (line.startsWith("#")) {
                int level = 0;
                while (level < line.length() && line.charAt(level) == '#') {
                    level++;
                }

                if (level <= 6) { // 只处理h1-h6
                    String title = line.substring(level).trim();
                    String anchor = title.toLowerCase()
                            .replaceAll("[^a-zA-Z0-9\u4e00-\u9fa5\s-]", "")
                            .replaceAll("\s+", "-");

                    String indent = "  ".repeat(level - 1);
                    toc.append(indent)
                            .append("- [")
                            .append(title)
                            .append("](#")
                            .append(anchor)
                            .append(")\n");
                }
            }
        }

        return toc.toString();
    }

    /**
     * 清理和格式化Markdown内容
     */
    public String cleanMarkdown(String markdown) {
        if (markdown == null) {
            return "";
        }

        // 移除多余的空行
        return markdown.replaceAll("\n{3,}", "\n\n").trim();
    }

    /**
     * 预处理Markdown内容，保持格式完整性
     */
    public String preprocessMarkdown(String markdown) {
        if (markdown == null || markdown.trim().isEmpty()) {
            return markdown;
        }

        // 标准化换行符
        markdown = markdown.replaceAll("\r\n", "\n").replaceAll("\r", "\n");

        // 保护代码块中的内容
        markdown = protectCodeBlocks(markdown);

        // 保护表格格式
        markdown = protectTableFormat(markdown);

        // 确保标题前后有适当的空行
        markdown = ensureHeadingSpacing(markdown);

        return markdown;
    }

    /**
     * 保护代码块格式
     */
    private String protectCodeBlocks(String markdown) {
        // 确保代码块前后有空行
        markdown = markdown.replaceAll("(?<!\n)```", "\n```");
        markdown = markdown.replaceAll("```(?!\n)", "```\n");
        return markdown;
    }

    /**
     * 保护表格格式
     */
    private String protectTableFormat(String markdown) {
        // 确保表格前后有空行
        String[] lines = markdown.split("\n");
        StringBuilder result = new StringBuilder();
        boolean inTable = false;

        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            boolean isTableLine = line.contains("|") && line.trim().length() > 0;

            if (isTableLine && !inTable) {
                // 表格开始，确保前面有空行
                if (result.length() > 0 && !result.toString().endsWith("\n\n")) {
                    result.append("\n");
                }
                inTable = true;
            } else if (!isTableLine && inTable) {
                // 表格结束，确保后面有空行
                inTable = false;
                result.append("\n");
            }

            result.append(line);
            if (i < lines.length - 1) {
                result.append("\n");
            }
        }

        return result.toString();
    }

    /**
     * 确保标题前后有适当的空行
     */
    private String ensureHeadingSpacing(String markdown) {
        String[] lines = markdown.split("\n");
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            boolean isHeading = line.trim().startsWith("#");

            if (isHeading && i > 0 && !lines[i - 1].trim().isEmpty()) {
                // 标题前添加空行
                result.append("\n");
            }

            result.append(line);

            if (isHeading && i < lines.length - 1 && !lines[i + 1].trim().isEmpty()) {
                // 标题后添加空行
                result.append("\n");
            }

            if (i < lines.length - 1) {
                result.append("\n");
            }
        }

        return result.toString();
    }
}